package com.example.esdemo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author zhanglei
 * @date 2023-01-12
 */
@Api(tags = "人类接口")
@RestController
@RequestMapping("/people")
public class PeopleController {

    @Autowired
    private TransportClient client;

    public static final String INDEX = "people";

    public static final String TYPE = "man";


    @GetMapping("/man/getById")
    @ApiOperation(httpMethod = "GET", value = "根据id查询")
    public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
        if (id.isEmpty()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        GetResponse result = this.client.prepareGet(INDEX, TYPE, id)
                .get();
        if (!result.isExists()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }


    @PostMapping("/man/add")
    @ApiOperation(httpMethod = "POST", value = "添加")
    public ResponseEntity add(@RequestParam(name = "name") String name,
                              @RequestParam(name = "age") int age,
                              @RequestParam(name = "country") String country,
                              @RequestParam(name = "date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String date) {

        try {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name", name)
                    .field("age", age)
                    .field("country", country)
                    .field("publish_date", date)
                    .endObject();

            IndexResponse result = this.client.prepareIndex(INDEX, TYPE)
                    .setSource(content)
                    .get();

            return new ResponseEntity(result.getId(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/man/delete")
    @ApiOperation(httpMethod = "DELETE", value = "删除")
    public ResponseEntity delete(@RequestParam(name = "id") String id) {

        DeleteResponse result = this.client.prepareDelete(INDEX, TYPE, id)
                .get();

        return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);

    }

    @PostMapping("/man/update")
    @ApiOperation(httpMethod = "POST", value = "更新")
    public ResponseEntity update(@RequestParam(name = "id") String id,
                                 @RequestParam(name = "name") String name,
                                 @RequestParam(name = "age") Integer age,
                                 @RequestParam(name = "country") String country,
                                 @RequestParam(name = "date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String date) {

        try {
            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
            if (name != null) {
                builder.field("name", name);
            }
            if (age != null) {
                builder.field("age", age);
            }
            if (country != null) {
                builder.field("country", country);
            }
            if (date != null) {
                builder.field("publish_date", date);
            }
            builder.endObject();
            UpdateRequest update = new UpdateRequest(INDEX, TYPE, id);
            update.doc(builder);

            UpdateResponse result = this.client.update(update).get();

            return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/man/query")
    @ApiOperation(httpMethod = "POST", value = "查询")
    public ResponseEntity add(@RequestParam(name = "name", required = false) String name,
                              @RequestParam(name = "gtAge", required = false) Integer gtAge,
                              @RequestParam(name = "ltAge", required = false) Integer ltAge,
                              @RequestParam(name = "country", required = false) String country,
                              @RequestParam(name = "countryQueryType", defaultValue = "1") Integer countryQueryType,
                              @RequestParam(name = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String date,
                              @RequestParam(name = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(name = "pageSize", required = false, defaultValue = "3") Integer pageSize) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (name != null) {
            boolQuery.must(QueryBuilders.matchQuery("name", name));
        }
        //年龄范围
        if (gtAge != null || ltAge != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
            if (gtAge != null && gtAge > 0) {
                rangeQuery.from(gtAge);
            }
            if (ltAge != null && ltAge > 0) {
                rangeQuery.to(ltAge);
            }
            boolQuery.filter(rangeQuery);
        }
        /*
           country模糊或者精确查询，字段类型：
           "country": {
                "type": "text",
                "fields": {
                "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                }
                }
            }
         */
        if (country != null) {
            if (countryQueryType == 1) {
                //精确查询
                boolQuery.must(QueryBuilders.termQuery("country.keyword", country));
            } else {
                //模糊查询，（有一个分词能匹配也会返回，根据匹配度）
                boolQuery.must(QueryBuilders.matchQuery("country", country));
            }
        }

        SearchRequestBuilder builder = this.client.prepareSearch(INDEX)
                .setTypes(TYPE)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(pageNum)
                .setSize(pageSize);

        System.out.println(builder);

        SearchResponse response = builder.get();
        ArrayList<Map<String, Object>> result = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            result.add(hit.getSourceAsMap());
        }

        return new ResponseEntity(result, HttpStatus.OK);

    }

}
